<!--
 * @Author: xiej
 * @Date: 2020-09-08 16:10:52
 * @LastEditors: Liu Zhiwang
 * @LastEditTime: 2021-07-07 16:22:43
 * @Description: 通用下载
-->
<template>
  <span
    v-loading="loading"
    element-loading-spinner="el-icon-loading"
    class="dsc-download"
    @click="download"
  >
    <slot />
  </span>
</template>
<script>
import { downloadFile } from '@/utils/public';
import { getToken } from '@/utils/auth';

export default {
  name: 'Download',
  props: {
    params: {
      type: Object,
      default() {
        return {
          url: '', // 下载路径
          fileName: '', // 文件名
          fileExt: '' // 后缀名
        };
      }
    },
    beforeDownload: Function
  },
  data() {
    return {
      loading: false
    };
  },
  methods: {
    download() {
      const hasToken = getToken() && getToken() !== 'undefined';
      if (!hasToken) {
        this.$confirm('系统识别您尚未登录，是否跳转登录页面？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            window.location.assign('/login');
          })
          .catch(() => {});
        return false;
      }
      this.loading = true;
      if (!this.beforeDownload) {
        return this.downloadFile(this.params);
      }

      const before = this.beforeDownload();
      if (before && before.then) {
        before.then(params => {
          this.downloadFile(params);
        });
      } else if (before) {
        this.downloadFile(before);
      }
    },
    downloadFile(item) {
      var fileName = '';
      if (item.fileName.indexOf(item.fileExt) !== -1) {
        fileName = item.fileName;
      } else {
        fileName = item.fileName + '.' + item.fileExt;
      }
      var param = {
        url: item.url,
        fileName: fileName
      };
      downloadFile(param).then(response => {
        this.loading = false;
      }).catch(_ => {
        this.loading = false;
      });
    }
  }
};
</script>
<style>
.dsc-download{
  cursor: pointer;
}
.dsc-download .el-loading-spinner{
  top: 0;
  margin: 0;
  line-height: initial;
}
</style>
